// common/request.js
const ENV = require('@/config/env.js')

module.exports = (vm) => {
  uni.$u.http.setConfig((config) => {
    config.baseURL = ENV.BASE_URL
    config.timeout = 8000
    config.header = { 'content-type': 'application/json' }
    config.custom = { auth: false } // 默认不需要 token
    return config
  })

  // 请求拦截
  uni.$u.http.interceptors.request.use((config) => {
    config.data = config.data || {}

    config.data.channel = vm.vuex_channel
    config.data.language = vm.vuex_language
    config.data.gender = vm.vuex_gender
    config.data.user_id = vm.vuex_user_id

    if (!config.data.hasOwnProperty('token')) {
      config.data.token = vm.vuex_token
    }

    if (config?.custom?.auth) {
      config.header.token = vm.vuex_token
    }

    console.log('请求地址：', config.baseURL + config.url)
    console.log('当前环境：', ENV.ENV_TEXT)

    return config
  }, (config) => Promise.reject(config))

  // 响应拦截
  uni.$u.http.interceptors.response.use((response) => {
    const data = response.data
    if (data.error === 2) {
      uni.$u.toast(data.msg || '登录失效，请重新登录')
      uni.navigateTo({ url: '/pages/index/login' })
      return
    }
    return data
  }, (response) => {
    console.warn('网络请求错误：', response)
    return Promise.reject(response)
  })
}
